2350 // Physical memory allocator, intended to allocate
2351 // memory for user processes, kernel stacks, page table pages,
2352 // and pipe buffers. Allocates 4096-byte pages.
2353 
2354 #include "types.h"
2355 #include "defs.h"
2356 #include "param.h"
2357 #include "mmu.h"
2358 #include "spinlock.h"
2359 
2360 struct run {
2361   struct run *next;
2362 };
2363 
2364 struct {
2365   struct spinlock lock;
2366   struct run *freelist;
2367 } kmem;
2368 
2369 // Initialize free list of physical pages.
2370 void
2371 kinit(void)
2372 {
2373   extern char end[];
2374 
2375   initlock(&kmem.lock, "kmem");
2376   char *p = (char*)PGROUNDUP((uint)end);
2377   for( ; p + PGSIZE - 1 < (char*) PHYSTOP; p += PGSIZE)
2378     kfree(p);
2379 }
2380 
2381 // Free the page of physical memory pointed at by v,
2382 // which normally should have been returned by a
2383 // call to kalloc().  (The exception is when
2384 // initializing the allocator; see kinit above.)
2385 void
2386 kfree(char *v)
2387 {
2388   struct run *r;
2389 
2390   if(((uint) v) % PGSIZE || (uint)v < 1024*1024 || (uint)v >= PHYSTOP)
2391     panic("kfree");
2392 
2393   // Fill with junk to catch dangling refs.
2394   memset(v, 1, PGSIZE);
2395 
2396 
2397 
2398 
2399 
2400   acquire(&kmem.lock);
2401   r = (struct run *) v;
2402   r->next = kmem.freelist;
2403   kmem.freelist = r;
2404   release(&kmem.lock);
2405 }
2406 
2407 // Allocate one 4096-byte page of physical memory.
2408 // Returns a pointer that the kernel can use.
2409 // Returns 0 if the memory cannot be allocated.
2410 char*
2411 kalloc()
2412 {
2413   struct run *r;
2414 
2415   acquire(&kmem.lock);
2416   r = kmem.freelist;
2417   if(r)
2418     kmem.freelist = r->next;
2419   release(&kmem.lock);
2420   return (char*) r;
2421 }
2422 
2423 
2424 
2425 
2426 
2427 
2428 
2429 
2430 
2431 
2432 
2433 
2434 
2435 
2436 
2437 
2438 
2439 
2440 
2441 
2442 
2443 
2444 
2445 
2446 
2447 
2448 
2449 
